# 此接口为用户的充值提现模块
from flask import Blueprint, jsonify, request
from importlib_metadata import method_cache
from models import User
from exts import db

bp = Blueprint('about_money', __name__, url_prefix="/about_money")

# 提现扣取的服务费用
def server_money(money):
    # 该目录下得先创建此文件
    with open("./public/server_money", "r+", encoding="utf8") as f:
        item_money = f.read()
        last_money = int(item_money) if item_money else 0 
        f.seek(0)
        end_money = str(int(last_money + money))
        f.write(end_money)
    return "ok"

# 提现
@bp.route("/withdraw", methods=["POST", "GET"])
def withdraw():
    params = request.get_json() # {'money': 158348, 'bankCardNum': '724717', 'password': '123', 'withdraw_money': 1000, 'email': '123@qq.com', 'username': '406973249'}
    # 验证用户是否存在，且支付密码正确
    user_item = User.query.filter_by(username=params["username"], password=params["password"]).first()
    if not user_item or user_item.email != params["email"]:
        return jsonify({
            "status": 400,
            "msg": "no user"
        })
    # 将用户的金币进行减操作
    end_money = user_item.money - params["withdraw_money"]
    user_item.money = end_money
    to_server_money = params["withdraw_money"] * 0.01 # 服务费
    to_user_money = params["withdraw_money"] * 0.99 # 用户到账金额
    user_money = end_money # 用户剩余金额
    # 将服务费存入文件
    if server_money(to_server_money) != "ok":
        return jsonify({
            "status": 500,
            "msg": "server error"
        })
    db.session.commit()
    return jsonify({
        "status": 200,
        "to_user_money": to_user_money,
        "to_server_money": to_server_money,
        "user_money": user_money
    })

# 充值
@bp.route("/recharge", methods=["POST", "GET"])
def recharge():
    params = request.get_json() # {'money': 9878, 'bankCardNum': '433311', 'password': '123', 'recharge_money': 1200, 'email': '123@qq.com', 'username': '406973249'}
    # 验证用户是否存在，且支付密码正确
    user_item = User.query.filter_by(username=params["username"], password=params["password"]).first()
    if not user_item or user_item.email != params["email"]:
        return jsonify({
            "status": 400,
            "msg": "no user"
        })

    # 将用户金额进行增加
    end_money = user_item.money  + params["recharge_money"]
    user_item.money = end_money
    db.session.commit() 
    return jsonify({
        "status": 200,
        "user_money": end_money
    })
